<template>
  <!-- 空容器：实际通知由 NotificationContainer (teleport 到 body) 渲染 -->
  <div />
</template>

<script setup lang="ts">
import { onMounted, watch } from 'vue'
import { addNotification, clearNotifications, notificationState } from '@/utils/notificationStore'
import { useSystemStateListener } from '@/composables/useSystemStateListener'
import { NOTIFICATION_WINDOW_CHANNELS } from '~shared/ipc-topic'

// 启动系统状态监听器
useSystemStateListener()
let offPush: (() => void) | null = null
let offClear: (() => void) | null = null
const old_size = ref('')

function measureAndResize() {
  // NotificationContainer 插件挂载在 #f2-notifications-root
  const host = document.querySelectorAll('.f2-toast-layer .f2-toast')
  if (host.length === 0) return
  let height = 80,
    width = 380
  for (const el of host) {
    height += el.getBoundingClientRect().height
    width = Math.max(width, el.getBoundingClientRect().width)
  }
  if (old_size.value !== width + 'x' + height) {
    console.log('resize', width, height)
    old_size.value = width + 'x' + height
    _pre_.ipcInvoke(NOTIFICATION_WINDOW_CHANNELS.SET_SIZE, { width, height })
  }
}

onMounted(() => {
  // 接收来自主进程的推送
  offPush = _pre_.ipcOn('notification-window:push', (payload: any) => {
    try {
      // 直接写入 store，由 NotificationContainer 负责渲染
      addNotification(payload)
      nextTick(measureAndResize)
    } catch (error) {
      console.error('[NotificationsWindow] push 处理失败:', error)
    }
  })
  offClear = _pre_.ipcOn('notification-window:clear', () => {
    clearNotifications()
    nextTick(measureAndResize)
  })

  // 监听数量变化，自动调整窗口高度
  watch(
    () => notificationState.items.length,
    (v, ov) =>
      nextTick(() => {
        if (v) measureAndResize()
        if (!v && ov) _pre_.ipcInvoke(NOTIFICATION_WINDOW_CHANNELS.CLEAR)
      }),
    { immediate: true }
  )
})

onBeforeUnmount(() => {
  offPush?.()
  offClear?.()
})
</script>

<style scoped>
:deep(html),
:deep(body),
:deep(#app) {
  background: transparent;
}

body {
  background: red;
}
</style>
